﻿//------------------------------------------------------------------------------------------------- 
// <copyright file="CreateWebApplication.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>Extends an new SPWebApplication.</summary>
//-------------------------------------------------------------------------------------------------
namespace Collaboris.Saf.Actions.Wss.WebApplication
{
    using System;
    using System.Collections.Generic;
    using System.Xml;

    using Engine;

    using Entities;

    using Microsoft.SharePoint.Administration;

    using SharePoint.Wss.Attributes;
    using SharePoint.Wss.WebApplications;

   
    [CollaborisClass(
        Title = "Extend Web Application",
        ReleaseStatus = ReleaseStatus.Stable,
        DisableDocumentation = false,
        ContactAuthorEmail = "Support@Collaboris.co.uk",
        Summary = "Extends an existing web application in IIS.",
        Remarks = "<b>important </b>This currently will not extend in all servers on the farm due the API being 'internal'.",
        ClassGuid = "{156E17A5-A7BA-4e1f-8A48-1BC341A7C662}",
        UndoImplemented = true
    )
    ]
    public class ExtendWebApplication : WSSActionBase<ExtendedWebApplicationInfo>
    {
        /// <summary>
        /// Undoes the action.
        /// </summary>
        /// <remarks>
        /// This will NOT remove IIS Web Sites in a Farm.
        /// </remarks>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected override ProcessStatus UndoAction(SafContext context, ExtendedWebApplicationInfo entity)
        {
            SPWebApplication webApplication = SPWebApplicationHelper.GetWebAppFromUrl(entity.WebAppUrl);

            if (webApplication != null)
            {
                //SPIisSettings iisSettings = SPWebApplicationHelper.GetExtendedSiteSettings(
                 //       webApplication, entity.SPUrlZone);

                Trace.TraceVerbose("Removing the Extended Web App for this Zone '{0}'", entity.SPUrlZone);
                webApplication.IisSettings.Remove(entity.SPUrlZone);
                if (entity.SPUrlZone != SPUrlZone.Default)  
                {
                    webApplication.AlternateUrls.UnsetResponseUrl(entity.SPUrlZone);
                    webApplication.AlternateUrls.Update();  
                }
                webApplication.Update();
            }

            return ProcessStatus.Success;
        }

        /// <summary>
        /// This will create the web using the information as specified in the
        /// <see cref="WebApplicationInfo"/>
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The data entityList.</param>
        /// <returns></returns>
        protected override ProcessStatus DoAction(SafContext context, ExtendedWebApplicationInfo entity)
        {
            this.Trace.TraceMethodStart("DoAction");
            
            SPWebApplication webApplication = SPWebApplicationHelper.GetWebAppFromUrl(entity.WebAppUrl);

            if (webApplication == null)
            {
                // cant find the Web App to Extend From so lets barf.
                throw new NullReferenceException(
                        string.Format("Cannot locate a Web Application at this Url : '{0}'", entity.WebAppUrl));
            }

            SPWebApplicationHelper.ExtendWebApplication(
                                        entity.WebAppUrl, 
                                        entity.WebAppName, 
                                        entity.HostHeader, 
                                        entity.Port.Value, 
                                        entity.LoadBalancedUrl, 
                                        entity.RootDirectory, 
                                        entity.AllowAnonymous.Value, 
                                        entity.UseNTLM.Value, 
                                        entity.UseSSL.Value, 
                                        entity.SPUrlZone);


            // TODO:
            //if (!SPWebHelper.WebExists(TargetWeb.Site, entity.Url))
            //{
            //    throw new ApplicationException(string.Format("This Web was not created : '{0}'", entity.Url));
            //}

            this.Trace.TraceMethodEnd("DoAction");

            return ProcessStatus.Success;
        }

        protected override bool IsValid(
            SafContext context,
            ExtendedWebApplicationInfo entity,
            ref System.Collections.Generic.List<ValidationError> errors,
            ProcessMode mode)
        {
            int currentCount = errors.Count;

            // Validate each object now.
             ValidateNullable(entity.Port, "ExtendedWebApplicationInfo.Port", ref errors);
            
            if (!entity.UseSSL.HasValue)
                entity.UseSSL = false;

            if (!entity.UseNTLM.HasValue)
                entity.UseNTLM = true;

            if (!entity.Overwrite.HasValue)
                entity.Overwrite = false;

            if (!entity.AllowAnonymous.HasValue)
                entity.AllowAnonymous = false;

            // Have we added errors ?
            return errors.Count == currentCount;
        }

    }
}
